package com.exam.admin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("SELECT username, password, enabled FROM t_admin WHERE username = ?")
                .authoritiesByUsernameQuery("SELECT username, authority FROM admin_authorities WHERE username = ?")
                .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(org.springframework.security.config.annotation.web.builders.HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                // 放行静态资源
                .antMatchers("/static/**", "/webjars/**").permitAll()
                // 放行登录、注册等页面
                .antMatchers("/admin/login", "/admin/register").permitAll()
                // 管理员首页及相关功能需要 ADMIN 权限
                .antMatchers("/admin/index", "/admin/teacher/**", "/admin/student/**", "/admin/course/**", "/admin/exam/**").hasRole("ADMIN")
                // 其他请求需要认证
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/admin/login")  // 自定义登录页面
                .loginProcessingUrl("/admin/login")  // 登录提交处理路径
                .defaultSuccessUrl("/admin/index", true)  // 登录成功跳转页面
                .failureUrl("/admin/login?error=true")  // 登录失败跳转页面
                .permitAll()
                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/admin/logout"))  // 退出登录路径
                .logoutSuccessUrl("/admin/login?logout=true")  // 退出登录成功跳转页面
                .permitAll()
                .and()
                .exceptionHandling()
                .accessDeniedPage("/access-denied");  // 权限不足跳转页面
    }
}